<template>
  <header class="app-header">
    <el-button @click="toggleDrawer" type="text">
      <el-icon :size="24"><Expand /></el-icon>
    </el-button>
    <el-dropdown @command="handleSelect">
      <span class="dropdown-title">
        {{ selectedTitle }}
        <el-icon class="dropdown-caret" :size="16">
          <CaretBottom />
        </el-icon>
      </span>
      <template #dropdown>
        <el-dropdown-menu v-if="dropdownOptions.length > 0">
          <el-dropdown-item
              v-for="item in dropdownOptions"
              :key="item.value"
              :command="item.value"
          >
            {{ item.label }} ({{ item.des }})
          </el-dropdown-item>
        </el-dropdown-menu>
        <div v-else class="loading-indicator">
          {{ isLoading ? '加载中...' : '暂无应用数据' }}
        </div>
      </template>
    </el-dropdown>
    <div class="header-right">
      <el-button @click="handlePlusClick" type="text">
        <el-icon :size="24"> <ChatDotRound /></el-icon>
      </el-button>
      <Drawer
          v-model="showDrawer"
          :conversations="currentConversations"
      />
    </div>
  </header>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { ElButton, ElIcon, ElDropdown, ElDropdownMenu, ElDropdownItem } from 'element-plus';
import { CirclePlus, Expand, CaretBottom } from '@element-plus/icons-vue';
import Drawer from '@/components/drawer/index.vue';
import { getAppListWithAttention, getAppRunningDetail } from '@/api/inter';

const showDrawer = ref(false);
const dropdownOptions = ref<{ label: string; value: number; des?: string }[]>([]);
const selectedTitle = ref('网优AI助手');
const isLoading = ref(true);
const currentConversations = ref([]);
const currentAppId = ref<number | null>(null); // 新增：跟踪当前选中的应用ID

// 组件挂载时调用接口
onMounted(async () => {
  try {
    isLoading.value = true;
    const response = await getAppListWithAttention();
    const appList = response.data || [];

    const formattedOptions = appList.map(item => ({
      label: item.name || '未知应用',
      value: item.id || 0,
      des: item.des || ''
    }));

    dropdownOptions.value = formattedOptions;

    if (formattedOptions.length > 0) {
      selectedTitle.value = formattedOptions[0].label;
      currentAppId.value = formattedOptions[0].value; // 初始化当前ID
      await fetchAppDetail(formattedOptions[0].value);
    }
  } catch (error: any) {
    console.error('获取应用列表失败:', error);
    uni.showToast({
      title: error.message || '获取应用列表失败',
      icon: 'none'
    });
  } finally {
    isLoading.value = false;
  }
});

const handleSelect = async (value: string | number) => {
  const selectedItem = dropdownOptions.value.find(item => item.value === Number(value));
  const selectedId = selectedItem?.value;

  // 仅当选择的ID与当前ID不同时执行
  if (selectedItem && selectedId !== currentAppId.value) {
    selectedTitle.value = selectedItem.label;
    console.log(`选中应用: ${selectedItem.label} (ID: ${selectedId})`);
    currentAppId.value = selectedId; // 更新当前ID
    await fetchAppDetail(selectedId);
  } else if (selectedItem) {
    console.log('选择的应用未变化，不触发更新');
  }
};

const toggleDrawer = () => {
  showDrawer.value = !showDrawer.value;
};

const handlePlusClick = () => {
  console.log('CirclePlus icon clicked');
};

async function fetchAppDetail(appId: number) {
  try {
    const data = await getAppRunningDetail(appId);
    console.log('应用详情:', data.data);
    console.log('会话信息:', data.conversations);

    currentConversations.value = data.conversations || [];
    // uni.showToast({ title: '获取会话成功', icon: 'success' });
  } catch (error: any) {
    console.error('获取应用详情失败:', error.message);
    uni.showToast({ title: error.message || '获取详情失败', icon: 'none' });
  }
}
</script>


<style scoped>
.app-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #ffffff;
  color: #888888;
  padding: 1rem;
  height: 36rpx;
  border-bottom: 1px solid #e4e7ed; /* 添加底部边框，增强视觉层次 */
}

.header-right {
  display: flex;
  align-items: center;
  gap: 1rem;
}

.el-button {
  color: #888888;
  font-size: 24px;
}

.dropdown-title {
  cursor: pointer;
  color: #303133; /* 标题文字使用深灰色，提高可读性 */
  font-size: 16px;
  padding: 8px 12px;
  border-radius: 4px;
  transition: background-color 0.2s;

  /* 添加悬停效果 */
  &:hover {
    background-color: #f5f7fa;
  }
}

.dropdown-title {
  display: flex;      /* 替换inline-flex或inline-block */
  align-items: center;/* 强制垂直居中 */
  gap: 4px;           /* 替代margin，更现代的间距控制方式 */
}

/* 移除图标自身的margin，改用gap统一控制 */
.dropdown-caret {
  margin: 0;
}
</style>